#!/usr/bin/env python
# encoding: utf-8
"""
vcd2sp.py

Created by Nathaniel Pinckney on 2008-05-24.
Copyright (c) 2008 Nathaniel Pinckney. All rights reserved.
"""

import sys
import os
from VCD import *
import VCDConfigParser

# TODO get_signal()/get_bus() just get
# TODO Config file should be able to specify bits of bus

def print_vectors():
	global config, vcd
	
	clkname = config.defaults()['CLK']
	clkdir = config.defaults()['CLKDIR']
	clkdelay = config.defaults()['CLKDELAY']
	resetname = config.defaults()['RESET']
	
	reset_count = 0
	run_count = 0
	
	# FIXME Have to set clk to something less arbitrary.... I think?	
	clk = '0'
	old_time = 0
	
	for time in vcd.times():
		vcd.set_time(time)
		oldclk = clk
		clk = vcd.get_signal(clkname)
		if (oldclk == '1' and clk == '0' and clkdir == 'fall') or \
		   (oldclk == '0' and clk == '1' and clkdir == 'rise'):
			if vcd.get_signal(resetname):
				reset_count += 1
			else:
				run_count += 1
			if clkdelay == '1':
				set_time(old_time)
			print_vector()
		old_time = time
		
# TODO Skip all clocks...
def print_vector():
	global config, vcd
	
	resetname = config.defaults()['RESET']
	
	arr = []
	for port in vcd.ports():
		if port in vcd.clks(): continue
		for bit in vcd.bits(port):
			

def main():
	global config, vcd
	
	config = VCDConfigParser.VCDConfigParser()
	config.read('example.conf')
	
	vcd = VCDParser()
	vcd.read('example.vcd')
	config.validate(vcd)
	
	# Print header
	print """\
;**********************************************************************
; %s.vec
; Digital Vector file for HSPICE stimulus
;
; Automatically generated by vcd2sp from '%s'
; Original .vcd file from %s (%s)
;**********************************************************************
""" % ("example", "example.vcd", vcd.version, vcd.date)

	arr = []
	for port in vcd.ports():
		if vcd.is_bus(port):
			for bit in vcd.bits(port):
				arr += ["%s[%s]" % (port, bit)]
		else:
			arr += [port]
	print "VNAME", ' '.join(arr)		

	arr = []
	for port in vcd.ports():
		# TODO case
		if config.get(port, 'type') == 'input':
			chr = 'i'
		elif config.get(port, 'type') == 'output':
			chr = 'o'
		elif config.get(port, 'type') == 'inout':
			chr = 'b'
		arr += [chr * vcd.port_size(port)]
	print "IO", ' '.join(arr)

	arr = []
	for port in vcd.ports():
		arr += ['1' * vcd.port_size(port)]
	print "RADIX", ' '.join(arr)
	
	print
	
	print_vectors()
	
	#print "Default's clock:", config.defaults()['CLK']
	
	#arr = []
	#for time in vcd.times():
	# 	print "At time", time
	# 	vcd.set_time(time)
	# 	for port in vcd.ports():
	# 		print "  Port", port, "of type", config.get(port,'type')
	# 		if vcd.is_bus(port):
	# 			for bit in vcd.bits(port):
	# 				print "    Bit", bit, "is", vcd.get_bus(port,bit)
	# 		else:
	# 			print "    is", vcd.get_signal(port)


if __name__ == '__main__':
	main()

